package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.AdsClickLog;
import com.atguigu.flink.chapter07.util.AtguiguUtil;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
/**
 * @Author lzc
 * @Date 2022/7/5 15:06
 */
public class Flink04_High_Project_Ads {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .readTextFile("input/AdClickLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new AdsClickLog(
                    Long.valueOf(data[0]),
                    Long.valueOf(data[1]),
                    data[2],
                    data[3],
                    Long.parseLong(data[4]) * 1000
                );
            })
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
    
                private ValueState<String> yesterdayState;
                private ValueState<Boolean> isBlackState;
                private ReducingState<Long> clickCountState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    clickCountState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Long>("clickCountState", Long::sum, Long.class));
                    isBlackState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("isBlackState", Boolean.class));
    
    
                    yesterdayState = getRuntimeContext().getState(new ValueStateDescriptor<String>("yesterdayState", String.class));
                }
                
                @Override
                public void processElement(AdsClickLog value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 如何判断跨天了?
                    // 一旦跨天, 清空状态
                    // 一个状态存储年月日, 如果这个条数据的日期与状态一样, 证明还是当天没有变, 不一样, 证明变天: 更新日期状态, 清空其他的2个状态
                    String today = AtguiguUtil.toDateString(value.getTimestamp());
                    String yesterday = yesterdayState.value();
    
                    if (!today.equals(yesterday)) {
                        clickCountState.clear();
                        isBlackState.clear();
                        
                        yesterdayState.update(today);
                    }
    
    
                    if (isBlackState.value() == null) {
                        clickCountState.add(1L);
                    }
                    Long count = clickCountState.get();
                    
                    String msg = "用户: " + value.getUserId() + " 对广告: " + value.getAdsId() + " 的点击量: " + count;
                    
                    if (isBlackState.value() == null && count > 99) {
                        isBlackState.update(true);
                        out.collect(msg + " 达到100, 加入到黑名单");
                    } else if (count <= 99) {
                        out.collect(msg);
                    }
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
